/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bsc.war.form;

import bsc.ejb.entity.Milestone;
import bsc.ejb.entity.MilestoneTracer;
import bsc.ejb.entity.Project;
import bsc.ejb.entity.Tracer;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.service.FileUtils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

//org.apache.commons.validator.GenericValidator
/**
 *
 * @author Miguel Angel
 */
public class UpdateDataProject extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        //String result = "Actualización de Datos del Proyecto Exitosa";
        boolean result = true;

        try {

            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

            //scorecardId="+scorecardId+"&title="+title+"&note="+note;
            Map<String, Object> parameterValues = FileUtils.getMultipartParameters(request);
            Object file = parameterValues.get("file");
            byte[] attachmentFile = file == null ? null : (byte[]) file;
            String attachmentFileName = (String) parameterValues.get("file_filename");

            //InputStream fis = Main.class.getResourceAsStream(nombreKPI);
            InputStream fis = new ByteArrayInputStream(attachmentFile);

            POIFSFileSystem fs = new POIFSFileSystem(fis);
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            int sheets = wb.getNumberOfSheets();

            for (int s = 0; s < sheets; s++) {
                //Hoja de trabajo
                //String ht= nombreKPI.substring(0,nombreKPI.length()-4 );
                HSSFSheet sheet = wb.getSheetAt(s);
                String ht = sheet.getSheetName();

                //Get id Project
                HSSFRow rowProject = sheet.getRow(0);
                Long idProject = (long) rowProject.getCell(1).getNumericCellValue();
                Project project = (Project) delegate.findScoreCard(idProject);


                //Milestones list
                List<Milestone> milestones = new ArrayList<Milestone>();

                HSSFRow rowMilestones = sheet.getRow(3);
                int rowMilestonesCount = rowMilestones.getLastCellNum();

                for (int i = 1; i < rowMilestonesCount; i++) {
                    String milestonesIdDescription[] = rowMilestones.getCell(i).getStringCellValue().split("-");
                    Long idMilestone = Long.parseLong(milestonesIdDescription[0]);
                    Milestone milestone = (Milestone) delegate.findTask(idMilestone);
                    //System.out.println("Milestone agregado: " + milestone.getName());
                    milestones.add(milestone);
                }

                //Tracer list

                //Obtengo la lista de dates

                List<Tracer> tracers = new ArrayList<Tracer>();
                Map<Tracer, HSSFRow> dateRow = new HashMap<Tracer, HSSFRow>();

                int inicioTracers = 4;
                int finTracers = sheet.getLastRowNum();

                for (int i = inicioTracers; i < finTracers + 1; i++) {
                    HSSFRow rowTracer = sheet.getRow(i);
                    String tracerString[] = rowTracer.getCell(0).getStringCellValue().split("-");
                    Long idTracer = Long.parseLong(tracerString[0]);
                    Tracer tracer = delegate.findTracer(idTracer);
                    System.out.println("Tracer: " + tracer.getName());
                    tracers.add(tracer);
                    dateRow.put(tracer, rowTracer);
                }
                //System.out.println("el tramaño de tracers es: " + tracers.size());

                //Se agregan los datos
                for (int i = 0; i < tracers.size(); i++) {
                    Tracer tracer = tracers.get(i);
                    //System.out.println("Ciclo de tracers");
                    for (int j = 0; j < milestones.size(); j++) {
                        //System.out.println("Ciclo de milestones");
                        Milestone milestone = milestones.get(j);
                        HSSFRow rowData = dateRow.get(tracer);
                        HSSFCell rowCell = rowData.getCell(j + 1, HSSFRow.CREATE_NULL_AS_BLANK);

                        if (rowCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                            double data = rowData.getCell(j + 1).getNumericCellValue();

                            if (tracer.getType() == Tracer.Type.PROGRESS) {
                                data = data / 100;
                            }
                            //System.out.println("El tracer: " +tracer.getName());
                            //System.out.println("El milestone: " + milestone.getName());
                            MilestoneTracer milestoneTracer = delegate.findMilestoneTracer(milestone, tracer);


                            if (milestoneTracer == null) {
                                MilestoneTracer mt = (MilestoneTracer) Factory.getBean("MilestoneTracer");
                                mt.setMilestone(milestone);
                                mt.setTracer(tracer);
                                if (sheet.getSheetName().equals("Real")) {
                                    mt.setRealValue(data);

                                } else if (sheet.getSheetName().equals("Goal")) {
                                    mt.setGoalValue(data);
                                }

                                delegate.createMilestoneTracer(mt);

                            } else {
                                //System.out.println("ENTRE AL UPDATE");
                                if (sheet.getSheetName().equals("Real")) {
                                    milestoneTracer.setRealValue(data);

                                } else if (sheet.getSheetName().equals("Meta")) {
                                    milestoneTracer.setGoalValue(data);
                                }
                                delegate.updateMilestoneTracer(milestoneTracer);

                            }
                        }


                    }

                }
            }

            result = true;

        } catch (Exception e) {
            e.printStackTrace();
            result = false;
        }
        request.setAttribute("result", result);
        return new ModelAndView("result");
    }
}
